<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock, Message, Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { userApi } from '@/api/user'

const router = useRouter()
const loginFormRef = ref(null)
const registerFormRef = ref(null)
const loading = ref(false)
const registerLoading = ref(false)
const showRegister = ref(false)

// 登录表单
const loginForm = reactive({
  account: '',
  password: ''
})

// 注册表单
const registerForm = reactive({
  account: '',
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

// 添加表单验证规则
const registerRules = {
  account: [
    { required: true, message: '请输入账户名', trigger: 'blur' },
    { min: 8, max: 16, message: '账户名长度需在 8 到 16 个字符之间', trigger: 'blur' },
    { 
      pattern: /^[a-zA-Z0-9]+$/, 
      message: '账户名只能包含字母和数字', 
      trigger: 'blur' 
    }
  ],
  username: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 16, message: '昵称长度需在 2 到 16 个字符之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, max: 16, message: '密码长度需在 8 到 16 个字符之间', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value === registerForm.account) {
          callback(new Error('密码不能与账户名相同'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 处理登录
const handleLogin = async () => {
  if (!loginForm.account || !loginForm.password) {
    ElMessage.warning('请输入账户和密码')
    return
  }
  
  loading.value = true
  try {
    const res = await userApi.login(loginForm)
    if (res.code === 1 && res.data) {
      const { user, token } = res.data
      localStorage.setItem('token', token)
      localStorage.setItem('user', JSON.stringify(user))
      
      ElMessage.success('登录成功')
      router.push('/')
    } else {
      ElMessage.error(res.msg || '登录失败')
    }
  } catch (error) {
    ElMessage.error('登录失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 切换表单显示
const toggleForm = () => {
  showRegister.value = !showRegister.value
  // 切换时重置表单
  if (showRegister.value) {
    registerForm.account = ''
    registerForm.username = ''
    registerForm.email = ''
    registerForm.password = ''
    registerForm.confirmPassword = ''
  } else {
    loginForm.account = ''
    loginForm.password = ''
  }
}

// 修改注册处理方法
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  try {
    await registerFormRef.value.validate()
    
    registerLoading.value = true
    
    // 构造注册数据，使用默认头像
    const registerData = {
      account: registerForm.account,
      username: registerForm.username,
      email: registerForm.email,
      password: registerForm.password,
      roleId: 2,  // 默认普通用户角色
      pic: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'  // 默认头像URL
    }
    
    const res = await userApi.register(registerData)
    if (res.code === 1) {
      ElMessage.success('注册成功，请登录')
      showRegister.value = false
      // 重置表单
      registerForm.account = ''
      registerForm.username = ''
      registerForm.email = ''
      registerForm.password = ''
      registerForm.confirmPassword = ''
    } else {
      ElMessage.error(res.msg || '注册失败')
    }
  } catch (error) {
    if (error.response?.data?.msg) {
      ElMessage.error(error.response.data.msg)
    } else {
      ElMessage.error('注册失败，请重试')
    }
  } finally {
    registerLoading.value = false
  }
}

// 修改退出登录处理
const handleLogout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('user')
  ElMessage.success('已退出登录')
  router.push('/login')
}

// 在 script setup 顶部添加
const apiUrl = import.meta.env.VITE_API_URL
</script>

<template>
  <div class="login-container">
    <div class="login-content">
      <div class="login-header">
        <img src="../assets/logo/Fast, forward.png" alt="Logo" class="logo">
        <h1 class="site-title">依辉视频</h1>
      </div>
      
      <el-card class="login-card">
        <h2 class="form-title">{{ showRegister ? '创建新账号' : '欢迎回来' }}</h2>
        
        <!-- 登录表单 -->
        <el-form v-if="!showRegister" :model="loginForm" ref="loginFormRef">
          <el-form-item>
            <el-input 
              v-model="loginForm.account" 
              :prefix-icon="User" 
              placeholder="账户/邮箱"
              size="large"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-input 
              v-model="loginForm.password" 
              :prefix-icon="Lock" 
              type="password" 
              placeholder="密码"
              size="large"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button 
              type="primary" 
              @click="handleLogin" 
              :loading="loading" 
              class="submit-button"
              size="large"
            >登录</el-button>
          </el-form-item>
          <div class="form-footer">
            <a href="javascript:;" @click="toggleForm">还没有账号？立即注册</a>
          </div>
        </el-form>

        <!-- 注册单 -->
        <el-form 
          v-else 
          :model="registerForm" 
          :rules="registerRules"
          ref="registerFormRef"
        >
          <el-form-item prop="account">
            <el-input 
              v-model="registerForm.account" 
              :prefix-icon="User" 
              placeholder="设置账户名（8-16位字母或数字）"
              size="large"
            ></el-input>
          </el-form-item>
          <el-form-item prop="username">
            <el-input 
              v-model="registerForm.username" 
              :prefix-icon="User" 
              placeholder="设置昵称（2-16位字符）"
              size="large"
            ></el-input>
          </el-form-item>
          <el-form-item prop="email">
            <el-input 
              v-model="registerForm.email" 
              :prefix-icon="Message" 
              placeholder="邮箱"
              size="large"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input 
              v-model="registerForm.password" 
              :prefix-icon="Lock" 
              type="password" 
              placeholder="设置密码（8-16位字符）"
              size="large"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <el-input 
              v-model="registerForm.confirmPassword" 
              :prefix-icon="Lock" 
              type="password" 
              placeholder="确认密码"
              size="large"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button 
              type="primary" 
              @click="handleRegister" 
              :loading="registerLoading" 
              class="submit-button"
              size="large"
            >注册</el-button>
          </el-form-item>
          <div class="form-footer">
            <a href="javascript:;" @click="toggleForm">已有账号？返回登录</a>
          </div>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<style>
@import '../css/login.css';
</style>
